package com.yourgroup.common.datasource;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component // 交给Spring管理
public class HikariPoolMonitor {

    // 注入Spring自动配置的Hikari数据源
    @Autowired
    private HikariDataSource hikariDataSource;

    /**
     * 获取连接池当前状态
     */
    public Map<String, Object> getPoolStatus() {
        Map<String, Object> status = new HashMap<>();
        // 通过Hikari的MXBean获取监控指标
        status.put(" pool名称 ", hikariDataSource.getPoolName());
        status.put("当前活跃连接数 ", hikariDataSource.getHikariPoolMXBean().getActiveConnections());
        status.put("空闲连接数 ", hikariDataSource.getHikariPoolMXBean().getIdleConnections());
        status.put("总连接数 ", hikariDataSource.getHikariPoolMXBean().getTotalConnections());
        status.put("等待连接的线程数 ", hikariDataSource.getHikariPoolMXBean().getThreadsAwaitingConnection());
        return status;
    }
}
